﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;

using Sunyi.Project.WebPoint.BusinessLogic;
using Sunyi.Project.WebPoint.Common;
using Sunyi.Project.WebPoint.DataContract;
using Sunyi.Project.WebPoint.Configuration;

namespace ActivitySystem.Web
{
    public partial class ActivitySystemDefaultMasterPage : MasterPage
    {
        PermissionManager permissionManager = new PermissionManager();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Session[WebPointGlobalConstant.Session_NavigationMenu] == null && Session[WebPointGlobalConstant.Session_CurrentUser] != null)
                {
                    try
                    {
                        CreateNavigationMenu();
                    }
                    catch (Exception ex)
                    {
                        ExceptionHandler.Handle(this, ex);
                    }
                }
                else
                {
                    Dictionary<string, MenuItem> menuItems = Session[WebPointGlobalConstant.Session_NavigationMenu] as Dictionary<string, MenuItem>;

                    if (menuItems != null)
                    {
                        foreach (var item in menuItems.Values) NavigationMenu.Items.Add(item);
                    }
                }
            }
        }

        protected void LinkButtonLogin_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect(EnvironmentSetting.LoginPageUrl, true);
            }
            catch (ThreadAbortException)
            {
                // Sometimes, the Response.Redirect throws thread abort exception when set the EndResponse parameter with "true".
                // Just ingore this exception.
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(this, ex);
            }
        }

        protected void LinkButtonLogout_Click(object sender, EventArgs e)
        {
            try
            {
                if (SystemConfiguration.PersonnelServiceEnabled)
                {
                    string userName = null;
                    if (Session[WebPointGlobalConstant.Session_CurrentUser] != null)
                    {
                        var currentUser = Session[WebPointGlobalConstant.Session_CurrentUser] as User;
                        if (currentUser != null) userName = currentUser.UserName;
                    }
                    else
                    {
                        userName = Thread.CurrentThread.Name;
                    }

                    if (!string.IsNullOrEmpty(userName))
                    {
                        var tokenManager = new TokenManager();
                        var token = tokenManager.SelectByUserName(userName);
                        if (token != null)
                        {
                            if (token.IssuedBy != SystemConfiguration.PlatForm[WebPointGlobalConstant.SystemName]) tokenManager.Erasure(token.Id);
                        }
                    }
                }

                Session.Clear();

                AuditLogger.Write(AuditLogOperationCode.Logout, this.GetType().Name);

                Response.Redirect(Request.UrlReferrer.AbsolutePath, true);
            }
            catch (ThreadAbortException)
            {
                // Sometimes, the Response.Redirect throws thread abort exception when set the EndResponse parameter with "true".
                // Just ingore this exception.
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(this, ex);
            }
        }

        #region Private Method

        private void CreateNavigationMenu()
        {
            PageManager pageManager = new PageManager();
            var pages = pageManager.SelectAll();

            var navigationBarPages = new List<Sunyi.Project.WebPoint.DataContract.Page>();
            var menuItemPages = new List<Sunyi.Project.WebPoint.DataContract.Page>();
            Dictionary<string, MenuItem> menuItems = new Dictionary<string, MenuItem>();

            User user = Session[WebPointGlobalConstant.Session_CurrentUser] as User;
            foreach (var page in pages)
            {
                if (!page.IsActive) continue;

                // Permission Check
                if (permissionManager.HasPermission(page.Url, user.UserName, PermissionType.Read))
                {
                    if (page.NavigationType == NavigationType.NavigationBar.ToString())
                    {
                        navigationBarPages.Add(page);
                    }
                    else if (page.NavigationType == NavigationType.MenuItem.ToString())
                    {
                        menuItemPages.Add(page);
                    }
                }
            }

            NavigationMenu.Items.Clear();

            navigationBarPages.Sort();
            // Add navigation bar pages.
            foreach (var page in navigationBarPages)
            {
                MenuItem item = new MenuItem(page.PageName, page.PageName);
                item.Selected = false;
                item.Selectable = true;
                item.NavigateUrl = page.Url;

                string category = page.Category;
                if (string.IsNullOrEmpty(page.Category)) category = WebPointGlobalConstant.Undefined;

                if (!menuItems.ContainsKey(category))
                {
                    menuItems.Add(page.Category, item);
                }

                NavigationMenu.Items.Add(item);
            }

            menuItemPages.Sort();

            // Add menu items.
            foreach (var page in menuItemPages)
            {
                MenuItem item = new MenuItem(page.PageName, page.PageName);
                item.Selected = false;
                item.Selectable = true;
                item.NavigateUrl = page.Url;

                if (menuItems.ContainsKey(page.Category) && menuItems[page.Category] != null)
                {
                    menuItems[page.Category].ChildItems.Add(item);
                }
            }

            // Put menu items into session for current user to improve performance.
            Session[WebPointGlobalConstant.Session_NavigationMenu] = menuItems;
        }

        #endregion
    }
}
